from fastapi import FastAPI, HTTPException, BackgroundTasks
from fastapi.responses import FileResponse
from pydantic import BaseModel
from typing import Optional, Dict, Any
import os

from agent.core import Agent
from agent.tools import ToolRegistry
from config.settings import settings

app = FastAPI(title="Agent Service API")
agent = Agent()
tool_registry = ToolRegistry()

class TaskRequest(BaseModel):
    description: str
    parameters: Optional[Dict[str, Any]] = None

class PPTRequest(BaseModel):
    topic: str
    output_filename: Optional[str] = None

@app.post("/agent/task")
async def create_task(task_request: TaskRequest):
    """Create a new task."""
    task = agent.create_task(task_request.description)
    return {"task_id": task.task_id, "status": task.status}

@app.get("/agent/task/{task_id}")
async def get_task(task_id: str):
    """Get task status and result."""
    task = agent.get_task(task_id)
    if not task:
        raise HTTPException(status_code=404, detail="Task not found")
    return task

@app.post("/agent/task/{task_id}/process")
async def process_task(task_id: str):
    """Process a specific task."""
    result = agent.process_task(task_id)
    if not result:
        raise HTTPException(status_code=404, detail="Task not found")
    return result

@app.get("/agent/tools")
async def list_tools():
    """List all available tools."""
    return {"tools": tool_registry.list_tools()}

@app.post("/agent/generate-ppt")
async def generate_ppt(request: PPTRequest, background_tasks: BackgroundTasks):
    """Generate a PPT presentation."""
    if not settings.DEEPSEEK_API_KEY:
        raise HTTPException(status_code=500, detail="DeepSeek API key not configured")

    result = tool_registry.generate_ppt(request.topic, request.output_filename)
    
    if result.get("status") == "error":
        raise HTTPException(status_code=500, detail=result["error"])
    
    return result

@app.get("/agent/download-ppt/{filename}")
async def download_ppt(filename: str):
    """Download a generated PPT file."""
    file_path = os.path.join(settings.PPT_OUTPUT_DIR, filename)
    
    if not os.path.exists(file_path):
        raise HTTPException(status_code=404, detail="Presentation not found")
        
    return FileResponse(
        file_path,
        media_type="application/vnd.openxmlformats-officedocument.presentationml.presentation",
        filename=filename
    ) 